package com.httpurlconnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private final String TAG = "MainActivity";
    private Button btnGet;
    private Button btnPost;
    private Button btnGetImg;
    private ImageView imageView;
    private EditText editPhone;
    private TextView textInfo;
    private Handler handler;
    private final int GET_IMG = 1001;
    private final int GET_INFO = 1002;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initFindViews();

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == GET_IMG) {
                    Bitmap bitmap = (Bitmap) msg.obj;
                    imageView.setImageBitmap(bitmap);
                    return true;
                } else if (msg.what == GET_INFO) {
                    String info = (String) msg.obj;
                    textInfo.setText(info);
                    return true;
                }
                return false;
            }
        });
        btnGetImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(
                        new Runnable() {
                            @Override
                            public void run() {
                                useHttpURLConnectionImg();
                            }
                        }
                ).start();
            }
        });
        btnGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = editPhone.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        useHttpURLConnectionGet(phone);
                    }
                }).start();
            }
        });

        btnPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = editPhone.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        useHttpURLConnectionPost(phone);
                    }
                }).start();
            }
        });
    }

    private void useHttpURLConnectionImg() {
        String strUrl = "https://img.gsdlcn.com/uploads/allimg/190309/1-1Z3091AT1.jpg";//图片url
        try {
            //创建Http链接
            URL url = new URL(strUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //获取HttpURLConnection请求码
            int code = httpURLConnection.getResponseCode();
            Log.e(TAG, "ImgResponseCode = " + code);

            getURLImage(httpURLConnection);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private void useHttpURLConnectionPost(String phone) {
        String phoneBaseUrl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";

        try {
            URL url = new URL(phoneBaseUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //设置HttpURLConnection的请求方法为post
            httpURLConnection.setRequestMethod("POST");
            //设置向HttpURLConnection输入
            httpURLConnection.setDoInput(true);
            //设置向HttpURLConnection输出
            httpURLConnection.setDoOutput(true);

            //向网页写入内容
            String body = "mobileCode=" + phone + "&userID=";
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
            bufferedWriter.write(body);
            bufferedWriter.flush();
            bufferedWriter.close();

            //获取HttpURLConnection请求码
            int code = httpURLConnection.getResponseCode();
            Log.e(TAG, "PostResponseCode = " + code);

            readHtmlContent(httpURLConnection);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void initFindViews() {
        btnGet = findViewById(R.id.btn_get);
        btnPost = findViewById(R.id.btn_post);
        btnGetImg = findViewById(R.id.btn_getImg);
        imageView = findViewById(R.id.imgView);
        editPhone = findViewById(R.id.edt_phone);
        textInfo = findViewById(R.id.txt_info);
    }

    private void useHttpURLConnectionGet(String phone) {
        String phoneBaseUrl = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo";
        String strUrl = phoneBaseUrl.concat("?mobileCode=").concat(phone).concat("&userID=");
        try {
            //创建Http链接
            URL url = new URL(strUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //获取HttpURLConnection请求码
            int code = httpURLConnection.getResponseCode();
            Log.e(TAG, "GetResponseCode = " + code);

            readHtmlContent(httpURLConnection);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void readHtmlContent(HttpURLConnection httpURLConnection) throws IOException {
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
        StringBuffer stringBuffer = new StringBuffer();
        String line = bufferedReader.readLine();
        while (line != null) {
            stringBuffer.append(line);
            line = bufferedReader.readLine();
        }
        Log.e(TAG, stringBuffer.toString());

        //通过消息发送给主线程
        Message message = Message.obtain();
        message.what = GET_INFO;
        message.obj = stringBuffer.toString();
        handler.sendMessage(message);
    }

    private void getURLImage(HttpURLConnection httpURLConnection) throws IOException {
        //获取图片并存入位图
        Bitmap bitmap = BitmapFactory.decodeStream(httpURLConnection.getInputStream());
        //通过消息发送给主线程
        Message message = Message.obtain();
        message.what = GET_IMG;
        message.obj = bitmap;
        handler.sendMessage(message);
    }
}
